<?php

require_once __DIR__ . '/vendor/autoload.php';

// 创建连接
$connection = new \PhpAmqpLib\Connection\AMQPStreamConnection(
    '192.168.50.10',
    5672,
    'guest',
    'guest'
);

// 建立信道
$channel = $connection->channel();

// 定义交换机，队列，路由名称
$exchangeName = 'exchangeTest';
$queueName = 'queueTest';
$routeKeyName = 'routeKeyTest';

$channel->exchange_declare(
    $exchangeName,
    \PhpAmqpLib\Exchange\AMQPExchangeType::DIRECT,
    false,
    true,
    false
);

$channel->queue_declare($queueName, false, true, false, false);

// 绑定队列和交换机和路由（绑定名称）
$channel->queue_bind($queueName, $exchangeName, $routeKeyName);

// 第二个参数代表：每次只消费1条
$channel->basic_qos(null, 1, null);

// 消息处理的逻辑回调函数
$callback = function(\PhpAmqpLib\Message\AMQPMessage $msg) {
    var_dump($msg->body);

    // 手动确认 ack，确保消息已经处理
    //$msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);

    if ($msg->body === 'quit') {
        $msg->delivery_info['channel']->basic_cancel($msg->delivery_info['consumer_tag']);
    }
};

$channel->basic_consume(
    $queueName,
    'consumer_tag',
    false,
    false,  // ** 这里要设为 false
    false,
    false,
    $callback
);

// 程序运行完成后关闭链接
function shutdown($channel, $connection)
{
    $channel->close();
    $connection->close();
}
register_shutdown_function('shutdown', $channel, $connection);

// 阻塞队列监听事件
while($channel->is_consuming()) {
    $channel->wait();
}